import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 39. Combination Sum 组合总和
 * https://leetcode.com/problems/combination-sum/description/
 */
class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        backtrack(0, target, candidates, ans, path);
        return ans;
    }
    private void backtrack(int i, int left, int[] candidates, List<List<Integer>> ans, List<Integer> path){
        if(left == 0){
            ans.add(new ArrayList<>(path));
            return;
        }
        if(left < candidates[i]){
            return;
        }
        for(int j = i; j < candidates.length; j++){
            path.add(candidates[j]);
            backtrack(j, left - candidates[j], candidates, ans, path);
            path.remove(path.size() - 1);
        }
    }
}